package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.Provinces;
import com.wzcl.app.dao.repository.ProvincesRepository;
import com.wzcl.app.model.common.MyPage;
import com.wzcl.app.model.common.WZCL;
import com.wzcl.app.model.dto.ProvinceDto;
import com.wzcl.app.service.ProvinceService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

;

@Log4j2
@Service
public class ProvinceServiceImpl implements ProvinceService {

    @Autowired
    private ProvincesRepository repository;


    @Override
    public Provinces getProvinceById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Provinces> getProvincesList(ProvinceDto provinceDto) {
        return repository.findAll(getSpecification(provinceDto), provinceDto.getSort());
    }

    @Override
    public MyPage<Provinces> getProvincesPage(ProvinceDto provinceDto) {
        return new MyPage<>(repository.findAll(getSpecification(provinceDto), provinceDto.getPageable()));
    }


    private Specification<Provinces> getSpecification(ProvinceDto provinceDto) {
        return new Specification<Provinces>() {
            @Override
            public Predicate toPredicate(Root<Provinces> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (provinceDto.getParentId() != null) {
                    predicates.add(criteriaBuilder.equal(root.get("parentId"), provinceDto.getParentId()));
                } else {
                    predicates.add(criteriaBuilder.isNull(root.get("parentId")));
                }
                predicates.add(criteriaBuilder.equal(root.get("state"), WZCL.STATE.NOT_DELETE));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }
}
